package org.zero.concurrency.demo.example.publish;

import lombok.extern.slf4j.Slf4j;
import org.zero.concurrency.demo.annotations.NotThreadSafe;

import java.util.Arrays;

/**
 * @program: concurrency-demo
 * @description: 不安全的对象发布示例
 * @author: 01
 * @create: 2018-10-16 16:21
 **/
@Slf4j
@NotThreadSafe
public class UnsafePublish {

    private String[] states = {"a", "b", "c"};

    /**
     * 过public访问级别发布了类的域，在类的外部，任何线程都可以访问这个域
     * 这样发布的对象是不安全的，因为我们无法得知其他线程是否会修改这个域导致该类里数据的错误
     *
     * @return String[]
     */
    public String[] getStates() {
        return states;
    }

    public static void main(String[] args) {
        UnsafePublish unsafePublish = new UnsafePublish();
        // 输出 [a, b, c]
        log.info("{}", Arrays.toString(unsafePublish.getStates()));

        unsafePublish.getStates()[0] = "d";
        // 输出 [d, b, c]
        log.info("{}", Arrays.toString(unsafePublish.getStates()));
    }
}
